<?php
/**
 * Created by PhpStorm.
 * User: Mysic
 * Date: 2020/10/30
 * Time: 2:00
 */

namespace app\mocks\extend;


use think\Env;

class MockRabbitmq
{
    protected static $instance = null;
    protected static $fileName;
    private function __construct(){}

    public static function instance()
    {
        if(!Env::get('mock.rabbitmq')) {
            return null;
        }
        if(self::$instance == null || (!self::$instance instanceof MockRabbitmq)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function send($msg, $exchange = '', $routeKey = '', $queue = '')
    {
        self::$fileName = RUNTIME_PATH . 'mock' . DS . $queue . '.queue';
        if (is_array($msg)) {
            $msg = json_encode($msg);// 将数组类型转换成JSON格式
        } else {
            $msg = trim(strval($msg));// 简单处理一下要发送的消息内容
        }
        $file = fopen(self::$fileName, 'a');
        fwrite($file, $msg . PHP_EOL);
        fclose($file);
    }

    public function run($consumeFunc, $exchange = '', $routeKey = '', $queue = '', $autoAck = true)
    {
        self::$fileName = RUNTIME_PATH . 'mock' . DS . $queue . '.queue';
        $file = fopen(self::$fileName, 'r+');
        $msg = new MockRabbitmqMsg();
        while(true) {
            rewind($file);
            while(!feof($file)) {
                $json = fgets($file);
                if($json){
                    $msg->setBody(trim($json));
                    call_user_func($consumeFunc, $msg);
                }
            }
            ftruncate($file, 0);
            sleep(1);
        }
    }
}


